/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package action.retail;

import cart.ShoppingCart;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
import database.TransactionDAO;
import java.util.Date;
import java.util.Map;
import model.Customer;
import model.Order;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Result;

/**
 *
 * @author Thai Ha Cong
 */
public class ProcessOrderAction extends ActionSupport {

    public ProcessOrderAction() {
    }

    @Override
    @Action(value = "processOrder", results = {
        @Result(name = "success", location = "/processOrderSuccess.jsp"),
        @Result(name = "error", location = "/shoppingCart.jsp"),
        @Result(name = "customer", location = "/redirect/rdrProcessOrderForm.jsp")
    })
    public String execute() throws Exception {
        Map session = ActionContext.getContext().getSession();
        Customer customer = (Customer) session.get("currentCustomer");

        if (customer == null) {
            return "customer";
        } else {
            ShoppingCart sc = (ShoppingCart) session.get("shoppingCart");
            Order order = sc.convertToOrder();
            Date date = new Date();

            order.setCustomer(customer);
            order.setCreateTime(date);
            order.setOrderStatus("Processing");

            TransactionDAO transactionDAO = new TransactionDAO();
            Integer createResult = transactionDAO.createOrder(order);
            
            if ( createResult!= null) {
                session.remove("shoppingCart");
                if (session.get("username") == null) {
                    session.remove("currentCustomer");
                }

                addActionMessage("" + createResult);

                return SUCCESS;
            } else {
                addActionError("Cannot Process Order (may be duplicate email). Contact Us for Help.");
                return ERROR;
            }
        }
    }
}